import Vue from 'vue'
import axios from 'axios';
import Qs from 'qs';

Vue.prototype.GetOpenID = function(callback) {

    if(!/micromessenger/i.test(navigator.userAgent)) return;
    //
    var that = this;
    var result = "";
    var code = GetQuery("code");
    var enterUrl = GetQuery('enterUrl');
    //判断是否有回传Code
    if (IsNullOrEmpty(code)) {

        var href = window.location.href;
        //为空获取授权页面
        let redirect = Qs.stringify({
            redirectrrl: encodeURI(href)
        })

        axios.post('/bhtong/wechart/main/getoauthurl.json', redirect).then(function (data) {
            if (data.data.tdata) {
                if (/http/.test(data.data.tdata)) {
                    that.$toast.success('等待授权');
                    window.location.href = data.data.tdata;
                } else {
                    result = data;
                }
            } else {
                that.$toast.fail('授权失败');
            }
        })
    } else {

        //不为空获取OpenID
        let wcode = Qs.stringify({
            code: code
        });

        
        axios.post("/bhtong/wechart/main/getopenidbycode.json", wcode).then(function (data) {
            if (data) {
                var openid = data.data.tdata.openid;
                var obj = {
                    key:"openid",
                    value:openid
                }
                that.$store.commit('setState', obj);

                that.$api.isaccountbind({
                    openid
                }).then(function (data) {
                    if (data.isaccountbind == '1') {
                        that.$api.wxautologin({
                            openid
                        }).then(function (data) {
                            const obj ={
                                openid:openid,
                                enterUrl:enterUrl ? enterUrl : 'order',
                            }
                            callback && callback(obj);
                        })
                    } else {

                    }
                });
            } else {
                that.$toast.fail('授权失败');
            }
        })
    }

    return result;

    // that.$api.wxautologin({
    //     openid: 'oIi1L6FevivTZ-jR-HwW4NZBWcYw'
    // }).then(function (data) {
    //     callback && callback();
    // })
};

function GetQuery (key) {
    var search = location.search.slice(1); //得到get方式提交的查询字符串
    var arr = search.split("&");
    for (var i = 0; i < arr.length; i++) {
        var ar = arr[i].split("=");
        if (ar[0] == key) {
            return ar[1];
        }
    }
    return "";
};

function IsNullOrEmpty (str) {
    var isOK = false;
    if (str == undefined || str == "") {
        isOK = true;
    }
    return isOK;
};
